package logic

import (
	"context"
	"errors"
	"goods_srv/cache"
	"goods_srv/models"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *CartAddLogic) CartAdd(in *goods.CartAddRequest) (*goods.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	//查询用户是否存在
	var u models.User
	u.ID = uint(in.UserId)
	err = u.GetUserId()
	if err != nil {
		logx.Error("用户查询失败")
		return nil, errors.New("用户查询失败")
	}

	if u.ID == 0 {
		logx.Error("用户不存在")
		return nil, errors.New("用户不存在")
	}

	//查询商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err = g.GetGoods()
	if err != nil {
		logx.Error("商品详情展示失败")
		return nil, errors.New("商品详情展示失败")
	}

	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}

	//判断单个餐品不超过200件
	if in.Num > 200 {
		logx.Error("单个餐品不超过200件")
		return nil, errors.New("单个餐品不超过200件")
	}

	//查看虚拟库存是否充足
	stock, err := cache.GetGoodsStock(int(in.GoodsId))
	if stock < in.Num {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	//查看购物车中是否有该商品
	if cache.ExistsGoods(int(in.UserId), int(in.GoodsId)) {
		//购物车中的商品数量自增
		err = cache.UpdateCartNum(int(in.UserId), int(in.GoodsId), int(in.Num))
	} else {
		//不存在则添加购物车
		goodsMap := map[string]interface{}{
			"user_id":     in.UserId,
			"goods_id":    in.GoodsId,
			"num":         in.Num,
			"goods_title": g.GoodsTitle,
			"goods_price": g.GoodsPrice,
		}
		err = cache.AddCart(int(in.UserId), int(in.GoodsId), goodsMap)
	}

	if err != nil {
		logx.Error("购物车添加失败")
		return nil, errors.New("购物车添加失败")
	}

	return &goods.CartAddResponse{}, nil
}
